var SuperFilter = {};

SuperFilter.firstLoad = true;

SuperFilter.init = function ($parent) {
	
	

    /* address change event*/
    $.address.change(function (e) {
		
        if (!SuperFilter.firstLoad || (SuperFilter.firstLoad && ($(location).attr('hash').replace('#/', '').replace('#', '')))) {
            SuperFilter.doFilter($parent, e.value);
        }
        SuperFilter.firstLoad = false;
    });
		SuperFilter.loadin($parent);
    
    /* render initial price slider */
   // SuperFilter.priceSlider($parent);
   SuperFilter.priceSlider($parent);
};

SuperFilter.loadin = function($parent){
	
	$(function () {
        /* sort order and limit */
        $('.sort select, .limit select').removeAttr('onchange').on('change', function (e) {
            SuperFilter.filter($parent);
            return false;
        });

        /* pagination change */
        $('.pagination').removeClass('hide');
        $('.pagination .links a').on('click', function (e) {
			
            $parent.find('.sf-page').val($(this).attr('href').split('page=')[1]);
            SuperFilter.filter($parent);
            return false;
        });
    });
	
	
    /* reset button event */
	//alert( $parent.html() );
    $parent.find('.sf-reset').on('click', function () {
        SuperFilter.reset($parent);
    });
		
    /* checkbox events */
	
    $parent.find('input[type="checkbox"]').on('click', function () {
		
        var $box = $(this).closest('.box');
		
		
        if ($box.hasClass('sf-single')) {
            $box.find('input[type="checkbox"]').not($(this)).removeAttr('checked');
        }
        setTimeout(function () { SuperFilter.filter($parent); }, 1);
    });
	
}
SuperFilter.reset = function ($parent) {
    var location = window.location.href;
    location = location.split("#");
    window.location.href = location[0];
};

SuperFilter.filter = function ($parent) {
    var filters = {};
    /* get selected filters */
		
    $parent.find('input:checked').each(function () {
        var name = $(this).attr('name');
        filters[name] = filters[name] || {
            name: name,
            group: name.replace(/\D/g, ''),
            filters: []
        };
        filters[name].filters.push({
            keyword: $(this).attr('data-keyword'),
            value: $(this).val()
        });
    });

    /* build url */
    var url_parts = [];
    for (var i in filters) {
        var keywords = [];
        var values = [];
        var type = filters[i].name[0];
        var group = filters[i].group;
        for (var j in filters[i].filters) {
            keywords.push(filters[i].filters[j].keyword);
            values.push(filters[i].filters[j].value);
        }
        url_parts.push(keywords.join(',') + '-' + (group ? '' + type + group + '-v' : type) + values.join(','));
    }

    /* add sort order */
    if ($('.sort').length > 0) {
        var value = $('.sort select option:selected').val().split('sort=')[1].split('&');
        url_parts.push('sort=' + value[0]);
        url_parts.push('order=' + value[1].replace('order=', ''));
    }

    /* add limit */
    if ($('.limit').length > 0) {
        url_parts.push('limit=' + $('.limit select option:selected').text());
    }

    /* add price */
    if ($parent.find('.sf-price').length > 0) {
        var minPrice = $parent.find('.sf-price .slider').attr('data-min');
        var maxPrice = $parent.find('.sf-price .slider').attr('data-max');
        if(minPrice && maxPrice && minPrice !== maxPrice){
            url_parts.push('minPrice=' + minPrice);
            url_parts.push('maxPrice=' + maxPrice);
        }
    }

    /* add pagination */
    var page = $parent.find('.sf-page').val();
    if (page) {
        url_parts.push('page=' + page);
    }

    /* change hash value */
    $.address.value(url_parts.join('/'));
};

SuperFilter.doFilter = function ($parent, url) {
    /* post data */
    var data = {
        filters: url,
        route: $parent.attr('data-route'),
        path: $parent.attr('data-path'),
		fullpath: $parent.attr('data-full-path')
    }

    /* set data for infinite scroll */
    window.J2FilterData = data;

    /* hide pagination */
    $('.pagination').addClass('hide');

    /* hide elements */
    //$parent.hide();
    $('.sf-loader').remove();
    $('.main-products.product-list, .main-products.product-grid').append('<div class="sf-loader"><span>' + $parent.attr('data-loading-text') + '</span></div>');

    /* filters */
    $.ajax({
        url: $parent.attr('data-filters-action'),
        type: 'post',
        async: false,
        data: data,
        success: function (response) {
			
            $parent.html($(response.replace(/\n/g, " ")).html());
            SuperFilter.setFilters($parent, url);
            $parent.show();
        }
    });
	
    /* products */
    $.ajax({
        url: $parent.attr('data-products-action'),
        type: 'post',
        data: data,
        success: function (response) {
            var $html = $('<div>' + response.replace(/\n/g, " ") + '</div>');
			//alert(response);
			$('.product-grid').html($html);
            $(".product-grid").html($html.find('.product-grid').html());

            
            if ($(".pagination").length > 0) {
                $(".pagination").html($html.find('.pagination').html());
            }else{
                $(".pagination").after($html.find('.pagination').html());
                $(".pagination").after($html.find('.pagination').html());
            }

            /*$('.pagination').removeClass('hide');
			 
        
			 $('.pagination .links a').on('click', function (e) {
						
						$parent.find('.sf-page').val($(this).attr('href').split('page=')[1]);
						SuperFilter.filter($parent);
						return false;
					});*/
		  SuperFilter.loadin($parent);
          
		  
		  setTimeout(function(){
                if(quickViewStatus){
                    enableQuickView();
                }
                $('.main-products .product-grid-item .image > a').prepend('<div class="p-over p-grid-over"> </div>');
                $('.main-products .product-list-item .image > a').prepend('<div class="p-over p-list-over"> </div>');

                disableAddToCartButton();
            }, 1);

            SuperFilter.setNavigation();
        }
    });
};

SuperFilter.setFilters = function ($parent, url) {
    var categoryPattern = /-c(((\d+)(,*))+)/;
    var manufacturerPattern = /-m(((\d+)(,*))+)/;
    var attributePattern = /-a(\d*)-v/;
    var optionPattern = /-o(\d*)-v/;

    var sort = null;
    var order = null;
    var minPrice = Math.floor(parseFloat($parent.find('.sf-price').attr('data-min-price')));
    var maxPrice = Math.ceil(parseFloat($parent.find('.sf-price').attr('data-max-price')));

    $.each(url.split('/'), function (index, part) {
        /* categories */
        if (categoryPattern.test(part)) {
            var values = part.split(categoryPattern);
            $.each(values[1].split(','), function (i, value) {
                $parent.find('.sf-category input[value="' + value + '"]').attr('checked', 'checked');
            });
            return;
        }

        /* manufacturers */
        if (manufacturerPattern.test(part)) {
            var values = part.split(manufacturerPattern);
            $.each(values[1].split(','), function (i, value) {
                $parent.find('.sf-manufacturer input[value="' + value + '"]').attr('checked', 'checked');
            });
            return;
        }

        /* attributes */
        if (attributePattern.test(part)) {
            var values = part.split(attributePattern);
            $.each(values[2].split(','), function (i, value) {
                $parent.find('.sf-attribute-' + values[1] + ' input[value="' + value + '"]').attr('checked', 'checked');
            });
            return;
        }

        /* options */
        if (optionPattern.test(part)) {
            var values = part.split(optionPattern);
            $.each(values[2].split(','), function (i, value) {
                $parent.find('.sf-option-' + values[1] + ' input[value="' + value + '"]').attr('checked', 'checked');
            });
            return;
        }

        /* limit */
        if (part.indexOf('limit=') !== -1) {
            $('.limit select option[value$="' + part + '"]').attr('selected', 'selected');
            return;
        }

        /* sort */
        if (part.indexOf('sort=') !== -1) {
            sort = part;
            return;
        };

        /* order */
        if (part.indexOf('order=') !== -1) {
            order = part;
            return;
        };

        /* min price */
        if (part.indexOf('minPrice=') !== -1) {
            minPrice = part.replace('minPrice=', '');
            return;
        }

        /* max price */
        if (part.indexOf('maxPrice=') !== -1) {
            maxPrice = part.replace('maxPrice=', '');
            return;
        }
    });

    /* check sort order select */
    $('.sort select option[value$="' + sort + "&" + order +'"]').attr('selected', 'selected');

    /* set slider values */
    if (minPrice && maxPrice) {
        $parent.find('.slider').attr('data-min-value', minPrice);
        $parent.find('.slider').attr('data-max-value', maxPrice);
        setTimeout(function () {
            SuperFilter.priceSlider($parent);
        }, 0);
    }

    /* add selected class */
    $parent.find('input:checked').each(function () {
        $(this).closest('label').addClass('sf-checked');
    });
};

SuperFilter.collision = function ($div1, $div2) {
    var x1 = $div1.offset().left;
    var w1 = 40;
    var r1 = x1 + w1;
    var x2 = $div2.offset().left;
    var w2 = 40;
    var r2 = x2 + w2;

    return !(r1 < x2 || x1 > r2);
}

SuperFilter.price = function ($parent, value) {
    var currency_left = $parent.attr('data-currency-left');
    var currency_right = $parent.attr('data-currency-right');
    var currency_decimal = $parent.attr('data-currency-decimal');
    var currency_thousand = $parent.attr('data-currency-thousand');
    value = value.toString().replace('.', currency_decimal).replace(/\B(?=(\d{3})+(?!\d))/g, currency_thousand);
	//alert(value);
    return currency_left ? (currency_left + value) : (value + currency_right);
	
}

SuperFilter.priceSlider = function ($parent) {
    $parent.find('.slider').slider({
        range: true,
        min: Math.floor(parseFloat($parent.find('.sf-price').attr('data-min-price'))),
        max: Math.ceil(parseFloat($parent.find('.sf-price').attr('data-max-price'))),
        values: [ parseFloat($parent.find('.slider').attr('data-min-value')), parseFloat($parent.find('.slider').attr('data-max-value')) ],
        slide: function(event, ui) {
            $('.ui-slider-handle:eq(0) .price-range-min').html(SuperFilter.price($parent, ui.values[0]));
            $('.ui-slider-handle:eq(1) .price-range-max').html(SuperFilter.price($parent, ui.values[1]));
            $('.price-range-both').html('<i>' + SuperFilter.price($parent, ui.values[0]) + ' - </i>' + SuperFilter.price($parent, ui.values[1]) );

            if ( ui.values[0] == ui.values[1] ) {
                $('.price-range-both i').css('display', 'none');
            } else {
                $('.price-range-both i').css('display', 'inline');
            }

            if (SuperFilter.collision($('.price-range-min'), $('.price-range-max')) == true) {
                $('.price-range-min, .price-range-max').css('opacity', '0');
                $('.price-range-both').css('display', 'block');
            } else {
                $('.price-range-min, .price-range-max').css('opacity', '1');
                $('.price-range-both').css('display', 'none');
            }
        },
        change: function (event, ui) {
            $(this).attr('data-min', ui.values[0]);
            $(this).attr('data-max', ui.values[1]);
            SuperFilter.filter($parent);
        }
    });

   /* $('.ui-slider-range').append('<span class="price-range-both value"><i>' + SuperFilter.price($parent, $parent.find('.slider').slider('values', 0 )) + ' - </i>' + SuperFilter.price($parent, $parent.find('.slider').slider('values', 1 )) + '</span>');*/
	
    $('.ui-slider-handle:eq(0)').html('<span class="price-range-min value">' + SuperFilter.price($parent, $parent.find('.slider').slider('values', 0 )) + '</span>');
    $('.ui-slider-handle:eq(1)').html('<span class="price-range-max value">' + SuperFilter.price($parent, $parent.find('.slider').slider('values', 1 )) + '</span>');
};
//
//SuperFilter.setNavigation = function () {
//    /* sort and limit events */
//    $('.sort select, .limit select').removeAttr('onchange');
//
//    /* display product grid */
//    display($.totalStorage('display'));
//};
var SuperFilter = {};

SuperFilter.firstLoad = true;

SuperFilter.init = function ($parent) {
	
	SuperFilter.priceSlider($parent);
    /* reset button event */
	//alert( $parent.html() );
    $parent.find('.sf-reset').on('click', function () {
        SuperFilter.reset($parent);
    });
		
    /* checkbox events */
	
    $parent.find('input[type="checkbox"]').on('click', function () {
		
        var $box = $(this).closest('.box');
		
		
        if ($box.hasClass('sf-single')) {
            $box.find('input[type="checkbox"]').not($(this)).removeAttr('checked');
        }
        setTimeout(function () { SuperFilter.filter($parent); }, 1);
    });

    /* address change event*/
    $.address.change(function (e) {
		
        if (!SuperFilter.firstLoad || (SuperFilter.firstLoad && ($(location).attr('hash').replace('#/', '').replace('#', '')))) {
            SuperFilter.doFilter($parent, e.value);
        }
        SuperFilter.firstLoad = false;
    });

    $(function () {
        /* sort order and limit */
        $('.sort select, .limit select').removeAttr('onchange').on('change', function (e) {
            SuperFilter.filter($parent);
            return false;
        });

        /* pagination change */
        $('.pagination').removeClass('hide');
        $('.pagination .links a').on('click', function (e) {
			alert('oda');
            $parent.find('.sf-page').val($(this).attr('href').split('page=')[1]);
            SuperFilter.filter($parent);
            return false;
        });
    });

    /* render initial price slider */
   // SuperFilter.priceSlider($parent);
};

SuperFilter.reset = function ($parent) {
    var location = window.location.href;
    location = location.split("#");
    window.location.href = location[0];
};

SuperFilter.filter = function ($parent) {
    var filters = {};
    /* get selected filters */
	
    $parent.find('input:checked').each(function () {
        var name = $(this).attr('name');
        filters[name] = filters[name] || {
            name: name,
            group: name.replace(/\D/g, ''),
            filters: []
        };
        filters[name].filters.push({
            keyword: $(this).attr('data-keyword'),
            value: $(this).val()
        });
    });

    /* build url */
    var url_parts = [];
    for (var i in filters) {
        var keywords = [];
        var values = [];
        var type = filters[i].name[0];
        var group = filters[i].group;
        for (var j in filters[i].filters) {
            keywords.push(filters[i].filters[j].keyword);
            values.push(filters[i].filters[j].value);
        }
        url_parts.push(keywords.join(',') + '-' + (group ? '' + type + group + '-v' : type) + values.join(','));
    }

    /* add sort order */
    if ($('.sort').length > 0) {
        var value = $('.sort select option:selected').val().split('sort=')[1].split('&');
        url_parts.push('sort=' + value[0]);
        url_parts.push('order=' + value[1].replace('order=', ''));
    }

    /* add limit */
    if ($('.limit').length > 0) {
        url_parts.push('limit=' + $('.limit select option:selected').text());
    }

    /* add price */
    if ($parent.find('.sf-price').length > 0) {
        var minPrice = $parent.find('.sf-price .slider').attr('data-min');
        var maxPrice = $parent.find('.sf-price .slider').attr('data-max');
        if(minPrice && maxPrice && minPrice !== maxPrice){
            url_parts.push('minPrice=' + minPrice);
            url_parts.push('maxPrice=' + maxPrice);
        }
    }

    /* add pagination */
    var page = $parent.find('.sf-page').val();
    if (page) {
        url_parts.push('page=' + page);
    }

    /* change hash value */
    $.address.value(url_parts.join('/'));
};

SuperFilter.doFilter = function ($parent, url) {
    /* post data */
    var data = {
        filters: url,
        route: $parent.attr('data-route'),
        path: $parent.attr('data-path'),
		fullpath: $parent.attr('data-full-path')
    }

    /* set data for infinite scroll */
    window.J2FilterData = data;

    /* hide pagination */
    $('.pagination').addClass('hide');

    /* hide elements */
    $parent.hide();
    $('.sf-loader').remove();
    $('.main-products.product-list, .main-products.product-grid').append('<div class="sf-loader"><span>' + $parent.attr('data-loading-text') + '</span></div>');

    /* filters */
    $.ajax({
        url: $parent.attr('data-filters-action'),
        type: 'post',
        async: false,
        data: data,
        success: function (response) {
            $parent.html($(response.replace(/\n/g, " ")).html());
            SuperFilter.setFilters($parent, url);
            $parent.show();
        }
    });
	
    /* products */
    $.ajax({
        url: $parent.attr('data-products-action'),
        type: 'post',
        data: data,
        success: function (response) {
            var $html = $('<div>' + response.replace(/\n/g, " ") + '</div>');
			//alert(response);
			$('.product-grid').html($html);
            $(".product-grid").html($html.find('.product-grid').html());

            
            if ($(".pagination").length > 0) {
                $(".pagination").html($html.find('.pagination').html());
            }else{
                $(".pagination").after($html.find('.pagination').html());
                $(".pagination").after($html.find('.pagination').html());
            }

            $('.pagination').removeClass('hide');

            setTimeout(function(){
                if(quickViewStatus){
                    enableQuickView();
                }
                $('.main-products .product-grid-item .image > a').prepend('<div class="p-over p-grid-over"> </div>');
                $('.main-products .product-list-item .image > a').prepend('<div class="p-over p-list-over"> </div>');

                disableAddToCartButton();
            }, 1);

            SuperFilter.setNavigation();
        }
    });
};

SuperFilter.setFilters = function ($parent, url) {
    var categoryPattern = /-c(((\d+)(,*))+)/;
    var manufacturerPattern = /-m(((\d+)(,*))+)/;
    var attributePattern = /-a(\d*)-v/;
    var optionPattern = /-o(\d*)-v/;

    var sort = null;
    var order = null;
    var minPrice = Math.floor(parseFloat($parent.find('.sf-price').attr('data-min-price')));
    var maxPrice = Math.ceil(parseFloat($parent.find('.sf-price').attr('data-max-price')));

    $.each(url.split('/'), function (index, part) {
        /* categories */
        if (categoryPattern.test(part)) {
            var values = part.split(categoryPattern);
            $.each(values[1].split(','), function (i, value) {
                $parent.find('.sf-category input[value="' + value + '"]').attr('checked', 'checked');
            });
            return;
        }

        /* manufacturers */
        if (manufacturerPattern.test(part)) {
            var values = part.split(manufacturerPattern);
            $.each(values[1].split(','), function (i, value) {
                $parent.find('.sf-manufacturer input[value="' + value + '"]').attr('checked', 'checked');
            });
            return;
        }

        /* attributes */
        if (attributePattern.test(part)) {
            var values = part.split(attributePattern);
            $.each(values[2].split(','), function (i, value) {
                $parent.find('.sf-attribute-' + values[1] + ' input[value="' + value + '"]').attr('checked', 'checked');
            });
            return;
        }

        /* options */
        if (optionPattern.test(part)) {
            var values = part.split(optionPattern);
            $.each(values[2].split(','), function (i, value) {
                $parent.find('.sf-option-' + values[1] + ' input[value="' + value + '"]').attr('checked', 'checked');
            });
            return;
        }

        /* limit */
        if (part.indexOf('limit=') !== -1) {
            $('.limit select option[value$="' + part + '"]').attr('selected', 'selected');
            return;
        }

        /* sort */
        if (part.indexOf('sort=') !== -1) {
            sort = part;
            return;
        };

        /* order */
        if (part.indexOf('order=') !== -1) {
            order = part;
            return;
        };

        /* min price */
        if (part.indexOf('minPrice=') !== -1) {
            minPrice = part.replace('minPrice=', '');
            return;
        }

        /* max price */
        if (part.indexOf('maxPrice=') !== -1) {
            maxPrice = part.replace('maxPrice=', '');
            return;
        }
    });

    /* check sort order select */
    $('.sort select option[value$="' + sort + "&" + order +'"]').attr('selected', 'selected');

    /* set slider values */
    if (minPrice && maxPrice) {
        $parent.find('.slider').attr('data-min-value', minPrice);
        $parent.find('.slider').attr('data-max-value', maxPrice);
        setTimeout(function () {
            SuperFilter.priceSlider($parent);
        }, 0);
    }

    /* add selected class */
    $parent.find('input:checked').each(function () {
        $(this).closest('label').addClass('sf-checked');
    });
};

SuperFilter.collision = function ($div1, $div2) {
    var x1 = $div1.offset().left;
    var w1 = 40;
    var r1 = x1 + w1;
    var x2 = $div2.offset().left;
    var w2 = 40;
    var r2 = x2 + w2;

    return !(r1 < x2 || x1 > r2);
}

SuperFilter.price = function ($parent, value) {
    var currency_left = $parent.attr('data-currency-left');
    var currency_right = $parent.attr('data-currency-right');
    var currency_decimal = $parent.attr('data-currency-decimal');
    var currency_thousand = $parent.attr('data-currency-thousand');
    value = value.toString().replace('.', currency_decimal).replace(/\B(?=(\d{3})+(?!\d))/g, currency_thousand);
	//alert(value);
    return currency_left ? (currency_left + value) : (value + currency_right);
	
}

SuperFilter.priceSlider = function ($parent) {
    $parent.find('.slider').slider({
        range: true,
        min: Math.floor(parseFloat($parent.find('.sf-price').attr('data-min-price'))),
        max: Math.ceil(parseFloat($parent.find('.sf-price').attr('data-max-price'))),
        values: [ parseFloat($parent.find('.slider').attr('data-min-value')), parseFloat($parent.find('.slider').attr('data-max-value')) ],
        slide: function(event, ui) {
            $('.ui-slider-handle:eq(0) .price-range-min').html(SuperFilter.price($parent, ui.values[0]));
            $('.ui-slider-handle:eq(1) .price-range-max').html(SuperFilter.price($parent, ui.values[1]));
            $('.price-range-both').html('<i>' + SuperFilter.price($parent, ui.values[0]) + ' - </i>' + SuperFilter.price($parent, ui.values[1]) );

            if ( ui.values[0] == ui.values[1] ) {
                $('.price-range-both i').css('display', 'none');
            } else {
                $('.price-range-both i').css('display', 'inline');
            }

            if (SuperFilter.collision($('.price-range-min'), $('.price-range-max')) == true) {
                $('.price-range-min, .price-range-max').css('opacity', '0');
                $('.price-range-both').css('display', 'block');
            } else {
                $('.price-range-min, .price-range-max').css('opacity', '1');
                $('.price-range-both').css('display', 'none');
            }
        },
        change: function (event, ui) {
            $(this).attr('data-min', ui.values[0]);
            $(this).attr('data-max', ui.values[1]);
            SuperFilter.filter($parent);
        }
    });

   /* $('.ui-slider-range').append('<span class="price-range-both value"><i>' + SuperFilter.price($parent, $parent.find('.slider').slider('values', 0 )) + ' - </i>' + SuperFilter.price($parent, $parent.find('.slider').slider('values', 1 )) + '</span>');*/
	
    $('.ui-slider-handle:eq(0)').html('<span class="price-range-min value">' + SuperFilter.price($parent, $parent.find('.slider').slider('values', 0 )) + '</span>');
    $('.ui-slider-handle:eq(1)').html('<span class="price-range-max value">' + SuperFilter.price($parent, $parent.find('.slider').slider('values', 1 )) + '</span>');
};
//
//SuperFilter.setNavigation = function () {
//    /* sort and limit events */
//    $('.sort select, .limit select').removeAttr('onchange');
//
//    /* display product grid */
//    display($.totalStorage('display'));
//};
var SuperFilter = {};

SuperFilter.firstLoad = true;

SuperFilter.init = function ($parent) {
	
	

    /* address change event*/
    $.address.change(function (e) {
		
        if (!SuperFilter.firstLoad || (SuperFilter.firstLoad && ($(location).attr('hash').replace('#/', '').replace('#', '')))) {
            SuperFilter.doFilter($parent, e.value);
        }
        SuperFilter.firstLoad = false;
    });
		SuperFilter.loadin($parent);
    
    /* render initial price slider */
   // SuperFilter.priceSlider($parent);
   SuperFilter.priceSlider($parent);
};

SuperFilter.loadin = function($parent){
	
	$(function () {
        /* sort order and limit */
        $('.sort select, .limit select').removeAttr('onchange').on('change', function (e) {
            SuperFilter.filter($parent);
            return false;
        });

        /* pagination change */
        $('.pagination').removeClass('hide');
        $('.pagination .links a').on('click', function (e) {
			
            $parent.find('.sf-page').val($(this).attr('href').split('page=')[1]);
            SuperFilter.filter($parent);
            return false;
        });
    });
	
	
    /* reset button event */
	//alert( $parent.html() );
    $parent.find('.sf-reset').on('click', function () {
        SuperFilter.reset($parent);
    });
		
    /* checkbox events */
	
    $parent.find('input[type="checkbox"]').on('click', function () {
		
        var $box = $(this).closest('.box');
		
		
        if ($box.hasClass('sf-single')) {
            $box.find('input[type="checkbox"]').not($(this)).removeAttr('checked');
        }
        setTimeout(function () { SuperFilter.filter($parent); }, 1);
    });
	
}
SuperFilter.reset = function ($parent) {
    var location = window.location.href;
    location = location.split("#");
    window.location.href = location[0];
};

SuperFilter.filter = function ($parent) {
    var filters = {};
    /* get selected filters */
		
    $parent.find('input:checked').each(function () {
        var name = $(this).attr('name');
        filters[name] = filters[name] || {
            name: name,
            group: name.replace(/\D/g, ''),
            filters: []
        };
        filters[name].filters.push({
            keyword: $(this).attr('data-keyword'),
            value: $(this).val()
        });
    });

    /* build url */
    var url_parts = [];
    for (var i in filters) {
        var keywords = [];
        var values = [];
        var type = filters[i].name[0];
        var group = filters[i].group;
        for (var j in filters[i].filters) {
            keywords.push(filters[i].filters[j].keyword);
            values.push(filters[i].filters[j].value);
        }
        url_parts.push(keywords.join(',') + '-' + (group ? '' + type + group + '-v' : type) + values.join(','));
    }

    /* add sort order */
    if ($('.sort').length > 0) {
        var value = $('.sort select option:selected').val().split('sort=')[1].split('&');
        url_parts.push('sort=' + value[0]);
        url_parts.push('order=' + value[1].replace('order=', ''));
    }

    /* add limit */
    if ($('.limit').length > 0) {
        url_parts.push('limit=' + $('.limit select option:selected').text());
    }

    /* add price */
    if ($parent.find('.sf-price').length > 0) {
        var minPrice = $parent.find('.sf-price .slider').attr('data-min');
        var maxPrice = $parent.find('.sf-price .slider').attr('data-max');
        if(minPrice && maxPrice && minPrice !== maxPrice){
            url_parts.push('minPrice=' + minPrice);
            url_parts.push('maxPrice=' + maxPrice);
        }
    }

    /* add pagination */
    var page = $parent.find('.sf-page').val();
    if (page) {
        url_parts.push('page=' + page);
    }

    /* change hash value */
    $.address.value(url_parts.join('/'));
};

SuperFilter.doFilter = function ($parent, url) {
    /* post data */
    var data = {
        filters: url,
        route: $parent.attr('data-route'),
        path: $parent.attr('data-path'),
		fullpath: $parent.attr('data-full-path')
    }

    /* set data for infinite scroll */
    window.J2FilterData = data;

    /* hide pagination */
    $('.pagination').addClass('hide');

    /* hide elements */
    //$parent.hide();
    $('.sf-loader').remove();
    $('.main-products.product-list, .main-products.product-grid').append('<div class="sf-loader"><span>' + $parent.attr('data-loading-text') + '</span></div>');

    /* filters */
    $.ajax({
        url: $parent.attr('data-filters-action'),
        type: 'post',
        async: false,
        data: data,
        success: function (response) {
			
            $parent.html($(response.replace(/\n/g, " ")).html());
            SuperFilter.setFilters($parent, url);
            $parent.show();
        }
    });
	
    /* products */
    $.ajax({
        url: $parent.attr('data-products-action'),
        type: 'post',
        data: data,
        success: function (response) {
            var $html = $('<div>' + response.replace(/\n/g, " ") + '</div>');
			//alert(response);
			$('.product-grid').html($html);
            $(".product-grid").html($html.find('.product-grid').html());

            
            if ($(".pagination").length > 0) {
                $(".pagination").html($html.find('.pagination').html());
            }else{
                $(".pagination").after($html.find('.pagination').html());
                $(".pagination").after($html.find('.pagination').html());
            }

            /*$('.pagination').removeClass('hide');
			 
        
			 $('.pagination .links a').on('click', function (e) {
						
						$parent.find('.sf-page').val($(this).attr('href').split('page=')[1]);
						SuperFilter.filter($parent);
						return false;
					});*/
		  SuperFilter.loadin($parent);
          
		  
		  setTimeout(function(){
                if(quickViewStatus){
                    enableQuickView();
                }
                $('.main-products .product-grid-item .image > a').prepend('<div class="p-over p-grid-over"> </div>');
                $('.main-products .product-list-item .image > a').prepend('<div class="p-over p-list-over"> </div>');

                disableAddToCartButton();
            }, 1);

            SuperFilter.setNavigation();
        }
    });
};

SuperFilter.setFilters = function ($parent, url) {
    var categoryPattern = /-c(((\d+)(,*))+)/;
    var manufacturerPattern = /-m(((\d+)(,*))+)/;
    var attributePattern = /-a(\d*)-v/;
    var optionPattern = /-o(\d*)-v/;

    var sort = null;
    var order = null;
    var minPrice = Math.floor(parseFloat($parent.find('.sf-price').attr('data-min-price')));
    var maxPrice = Math.ceil(parseFloat($parent.find('.sf-price').attr('data-max-price')));

    $.each(url.split('/'), function (index, part) {
        /* categories */
        if (categoryPattern.test(part)) {
            var values = part.split(categoryPattern);
            $.each(values[1].split(','), function (i, value) {
                $parent.find('.sf-category input[value="' + value + '"]').attr('checked', 'checked');
            });
            return;
        }

        /* manufacturers */
        if (manufacturerPattern.test(part)) {
            var values = part.split(manufacturerPattern);
            $.each(values[1].split(','), function (i, value) {
                $parent.find('.sf-manufacturer input[value="' + value + '"]').attr('checked', 'checked');
            });
            return;
        }

        /* attributes */
        if (attributePattern.test(part)) {
            var values = part.split(attributePattern);
            $.each(values[2].split(','), function (i, value) {
                $parent.find('.sf-attribute-' + values[1] + ' input[value="' + value + '"]').attr('checked', 'checked');
            });
            return;
        }

        /* options */
        if (optionPattern.test(part)) {
            var values = part.split(optionPattern);
            $.each(values[2].split(','), function (i, value) {
                $parent.find('.sf-option-' + values[1] + ' input[value="' + value + '"]').attr('checked', 'checked');
            });
            return;
        }

        /* limit */
        if (part.indexOf('limit=') !== -1) {
            $('.limit select option[value$="' + part + '"]').attr('selected', 'selected');
            return;
        }

        /* sort */
        if (part.indexOf('sort=') !== -1) {
            sort = part;
            return;
        };

        /* order */
        if (part.indexOf('order=') !== -1) {
            order = part;
            return;
        };

        /* min price */
        if (part.indexOf('minPrice=') !== -1) {
            minPrice = part.replace('minPrice=', '');
            return;
        }

        /* max price */
        if (part.indexOf('maxPrice=') !== -1) {
            maxPrice = part.replace('maxPrice=', '');
            return;
        }
    });

    /* check sort order select */
    $('.sort select option[value$="' + sort + "&" + order +'"]').attr('selected', 'selected');

    /* set slider values */
    if (minPrice && maxPrice) {
        $parent.find('.slider').attr('data-min-value', minPrice);
        $parent.find('.slider').attr('data-max-value', maxPrice);
        setTimeout(function () {
            SuperFilter.priceSlider($parent);
        }, 0);
    }

    /* add selected class */
    $parent.find('input:checked').each(function () {
        $(this).closest('label').addClass('sf-checked');
    });
};

SuperFilter.collision = function ($div1, $div2) {
    var x1 = $div1.offset().left;
    var w1 = 40;
    var r1 = x1 + w1;
    var x2 = $div2.offset().left;
    var w2 = 40;
    var r2 = x2 + w2;

    return !(r1 < x2 || x1 > r2);
}

SuperFilter.price = function ($parent, value) {
    var currency_left = $parent.attr('data-currency-left');
    var currency_right = $parent.attr('data-currency-right');
    var currency_decimal = $parent.attr('data-currency-decimal');
    var currency_thousand = $parent.attr('data-currency-thousand');
    value = value.toString().replace('.', currency_decimal).replace(/\B(?=(\d{3})+(?!\d))/g, currency_thousand);
	//alert(value);
    return currency_left ? (currency_left + value) : (value + currency_right);
	
}

SuperFilter.priceSlider = function ($parent) {
    $parent.find('.slider').slider({
        range: true,
        min: Math.floor(parseFloat($parent.find('.sf-price').attr('data-min-price'))),
        max: Math.ceil(parseFloat($parent.find('.sf-price').attr('data-max-price'))),
        values: [ parseFloat($parent.find('.slider').attr('data-min-value')), parseFloat($parent.find('.slider').attr('data-max-value')) ],
        slide: function(event, ui) {
            $('.ui-slider-handle:eq(0) .price-range-min').html(SuperFilter.price($parent, ui.values[0]));
            $('.ui-slider-handle:eq(1) .price-range-max').html(SuperFilter.price($parent, ui.values[1]));
            $('.price-range-both').html('<i>' + SuperFilter.price($parent, ui.values[0]) + ' - </i>' + SuperFilter.price($parent, ui.values[1]) );

            if ( ui.values[0] == ui.values[1] ) {
                $('.price-range-both i').css('display', 'none');
            } else {
                $('.price-range-both i').css('display', 'inline');
            }

            if (SuperFilter.collision($('.price-range-min'), $('.price-range-max')) == true) {
                $('.price-range-min, .price-range-max').css('opacity', '0');
                $('.price-range-both').css('display', 'block');
            } else {
                $('.price-range-min, .price-range-max').css('opacity', '1');
                $('.price-range-both').css('display', 'none');
            }
        },
        change: function (event, ui) {
            $(this).attr('data-min', ui.values[0]);
            $(this).attr('data-max', ui.values[1]);
            SuperFilter.filter($parent);
        }
    });

   /* $('.ui-slider-range').append('<span class="price-range-both value"><i>' + SuperFilter.price($parent, $parent.find('.slider').slider('values', 0 )) + ' - </i>' + SuperFilter.price($parent, $parent.find('.slider').slider('values', 1 )) + '</span>');*/
	
    $('.ui-slider-handle:eq(0)').html('<span class="price-range-min value">' + SuperFilter.price($parent, $parent.find('.slider').slider('values', 0 )) + '</span>');
    $('.ui-slider-handle:eq(1)').html('<span class="price-range-max value">' + SuperFilter.price($parent, $parent.find('.slider').slider('values', 1 )) + '</span>');
};
//
//SuperFilter.setNavigation = function () {
//    /* sort and limit events */
//    $('.sort select, .limit select').removeAttr('onchange');
//
//    /* display product grid */
//    display($.totalStorage('display'));
//};
var SuperFilter = {};

SuperFilter.firstLoad = true;

SuperFilter.init = function ($parent) {
	
	SuperFilter.priceSlider($parent);
    /* reset button event */
	//alert( $parent.html() );
    $parent.find('.sf-reset').on('click', function () {
        SuperFilter.reset($parent);
    });
		
    /* checkbox events */
	
    $parent.find('input[type="checkbox"]').on('click', function () {
		
        var $box = $(this).closest('.box');
		
		
        if ($box.hasClass('sf-single')) {
            $box.find('input[type="checkbox"]').not($(this)).removeAttr('checked');
        }
        setTimeout(function () { SuperFilter.filter($parent); }, 1);
    });

    /* address change event*/
    $.address.change(function (e) {
		
        if (!SuperFilter.firstLoad || (SuperFilter.firstLoad && ($(location).attr('hash').replace('#/', '').replace('#', '')))) {
            SuperFilter.doFilter($parent, e.value);
        }
        SuperFilter.firstLoad = false;
    });

    $(function () {
        /* sort order and limit */
        $('.sort select, .limit select').removeAttr('onchange').on('change', function (e) {
            SuperFilter.filter($parent);
            return false;
        });

        /* pagination change */
        $('.pagination').removeClass('hide');
        $('.pagination .links a').on('click', function (e) {
            $parent.find('.sf-page').val($(this).attr('href').split('page=')[1]);
            SuperFilter.filter($parent);
            return false;
        });
    });

    /* render initial price slider */
   // SuperFilter.priceSlider($parent);
};

SuperFilter.reset = function ($parent) {
    var location = window.location.href;
    location = location.split("#");
    window.location.href = location[0];
};

SuperFilter.filter = function ($parent) {
    var filters = {};
    /* get selected filters */
	
    $parent.find('input:checked').each(function () {
        var name = $(this).attr('name');
        filters[name] = filters[name] || {
            name: name,
            group: name.replace(/\D/g, ''),
            filters: []
        };
        filters[name].filters.push({
            keyword: $(this).attr('data-keyword'),
            value: $(this).val()
        });
    });

    /* build url */
    var url_parts = [];
    for (var i in filters) {
        var keywords = [];
        var values = [];
        var type = filters[i].name[0];
        var group = filters[i].group;
        for (var j in filters[i].filters) {
            keywords.push(filters[i].filters[j].keyword);
            values.push(filters[i].filters[j].value);
        }
        url_parts.push(keywords.join(',') + '-' + (group ? '' + type + group + '-v' : type) + values.join(','));
    }

    /* add sort order */
    if ($('.sort').length > 0) {
        var value = $('.sort select option:selected').val().split('sort=')[1].split('&');
        url_parts.push('sort=' + value[0]);
        url_parts.push('order=' + value[1].replace('order=', ''));
    }

    /* add limit */
    if ($('.limit').length > 0) {
        url_parts.push('limit=' + $('.limit select option:selected').text());
    }

    /* add price */
    if ($parent.find('.sf-price').length > 0) {
        var minPrice = $parent.find('.sf-price .slider').attr('data-min');
        var maxPrice = $parent.find('.sf-price .slider').attr('data-max');
        if(minPrice && maxPrice && minPrice !== maxPrice){
            url_parts.push('minPrice=' + minPrice);
            url_parts.push('maxPrice=' + maxPrice);
        }
    }

    /* add pagination */
    var page = $parent.find('.sf-page').val();
    if (page) {
        url_parts.push('page=' + page);
    }

    /* change hash value */
    $.address.value(url_parts.join('/'));
};

SuperFilter.doFilter = function ($parent, url) {
    /* post data */
    var data = {
        filters: url,
        route: $parent.attr('data-route'),
        path: $parent.attr('data-path')
    }

    /* set data for infinite scroll */
    window.J2FilterData = data;

    /* hide pagination */
    $('.pagination').addClass('hide');

    /* hide elements */
    $parent.hide();
    $('.sf-loader').remove();
    $('.main-products.product-list, .main-products.product-grid').append('<div class="sf-loader"><span>' + $parent.attr('data-loading-text') + '</span></div>');

    /* filters */
    $.ajax({
        url: $parent.attr('data-filters-action'),
        type: 'post',
        async: false,
        data: data,
        success: function (response) {
            $parent.html($(response.replace(/\n/g, " ")).html());
            SuperFilter.setFilters($parent, url);
            $parent.show();
        }
    });

    /* products */
    $.ajax({
        url: $parent.attr('data-products-action'),
        type: 'post',
        data: data,
        success: function (response) {
            var $html = $('<div>' + response.replace(/\n/g, " ") + '</div>');
			//alert(response);
			$('.product-grid').html($html);
            $(".product-grid").html($html.find('.product-grid').html());

            
            if ($(".pagination").length > 0) {
                $(".pagination").html($html.find('.pagination').html());
            }else{
                $(".pagination").after($html.find('.pagination').html());
                $(".pagination").after($html.find('.pagination').html());
            }

            $('.pagination').removeClass('hide');

            setTimeout(function(){
                if(quickViewStatus){
                    enableQuickView();
                }
                $('.main-products .product-grid-item .image > a').prepend('<div class="p-over p-grid-over"> </div>');
                $('.main-products .product-list-item .image > a').prepend('<div class="p-over p-list-over"> </div>');

                disableAddToCartButton();
            }, 1);

            SuperFilter.setNavigation();
        }
    });
};

SuperFilter.setFilters = function ($parent, url) {
    var categoryPattern = /-c(((\d+)(,*))+)/;
    var manufacturerPattern = /-m(((\d+)(,*))+)/;
    var attributePattern = /-a(\d*)-v/;
    var optionPattern = /-o(\d*)-v/;

    var sort = null;
    var order = null;
    var minPrice = Math.floor(parseFloat($parent.find('.sf-price').attr('data-min-price')));
    var maxPrice = Math.ceil(parseFloat($parent.find('.sf-price').attr('data-max-price')));

    $.each(url.split('/'), function (index, part) {
        /* categories */
        if (categoryPattern.test(part)) {
            var values = part.split(categoryPattern);
            $.each(values[1].split(','), function (i, value) {
                $parent.find('.sf-category input[value="' + value + '"]').attr('checked', 'checked');
            });
            return;
        }

        /* manufacturers */
        if (manufacturerPattern.test(part)) {
            var values = part.split(manufacturerPattern);
            $.each(values[1].split(','), function (i, value) {
                $parent.find('.sf-manufacturer input[value="' + value + '"]').attr('checked', 'checked');
            });
            return;
        }

        /* attributes */
        if (attributePattern.test(part)) {
            var values = part.split(attributePattern);
            $.each(values[2].split(','), function (i, value) {
                $parent.find('.sf-attribute-' + values[1] + ' input[value="' + value + '"]').attr('checked', 'checked');
            });
            return;
        }

        /* options */
        if (optionPattern.test(part)) {
            var values = part.split(optionPattern);
            $.each(values[2].split(','), function (i, value) {
                $parent.find('.sf-option-' + values[1] + ' input[value="' + value + '"]').attr('checked', 'checked');
            });
            return;
        }

        /* limit */
        if (part.indexOf('limit=') !== -1) {
            $('.limit select option[value$="' + part + '"]').attr('selected', 'selected');
            return;
        }

        /* sort */
        if (part.indexOf('sort=') !== -1) {
            sort = part;
            return;
        };

        /* order */
        if (part.indexOf('order=') !== -1) {
            order = part;
            return;
        };

        /* min price */
        if (part.indexOf('minPrice=') !== -1) {
            minPrice = part.replace('minPrice=', '');
            return;
        }

        /* max price */
        if (part.indexOf('maxPrice=') !== -1) {
            maxPrice = part.replace('maxPrice=', '');
            return;
        }
    });

    /* check sort order select */
    $('.sort select option[value$="' + sort + "&" + order +'"]').attr('selected', 'selected');

    /* set slider values */
    if (minPrice && maxPrice) {
        $parent.find('.slider').attr('data-min-value', minPrice);
        $parent.find('.slider').attr('data-max-value', maxPrice);
        setTimeout(function () {
            SuperFilter.priceSlider($parent);
        }, 0);
    }

    /* add selected class */
    $parent.find('input:checked').each(function () {
        $(this).closest('label').addClass('sf-checked');
    });
};

SuperFilter.collision = function ($div1, $div2) {
    var x1 = $div1.offset().left;
    var w1 = 40;
    var r1 = x1 + w1;
    var x2 = $div2.offset().left;
    var w2 = 40;
    var r2 = x2 + w2;

    return !(r1 < x2 || x1 > r2);
}

SuperFilter.price = function ($parent, value) {
    var currency_left = $parent.attr('data-currency-left');
    var currency_right = $parent.attr('data-currency-right');
    var currency_decimal = $parent.attr('data-currency-decimal');
    var currency_thousand = $parent.attr('data-currency-thousand');
    value = value.toString().replace('.', currency_decimal).replace(/\B(?=(\d{3})+(?!\d))/g, currency_thousand);
	//alert(value);
    return currency_left ? (currency_left + value) : (value + currency_right);
	
}

SuperFilter.priceSlider = function ($parent) {
    $parent.find('.slider').slider({
        range: true,
        min: Math.floor(parseFloat($parent.find('.sf-price').attr('data-min-price'))),
        max: Math.ceil(parseFloat($parent.find('.sf-price').attr('data-max-price'))),
        values: [ parseFloat($parent.find('.slider').attr('data-min-value')), parseFloat($parent.find('.slider').attr('data-max-value')) ],
        slide: function(event, ui) {
            $('.ui-slider-handle:eq(0) .price-range-min').html(SuperFilter.price($parent, ui.values[0]));
            $('.ui-slider-handle:eq(1) .price-range-max').html(SuperFilter.price($parent, ui.values[1]));
            $('.price-range-both').html('<i>' + SuperFilter.price($parent, ui.values[0]) + ' - </i>' + SuperFilter.price($parent, ui.values[1]) );

            if ( ui.values[0] == ui.values[1] ) {
                $('.price-range-both i').css('display', 'none');
            } else {
                $('.price-range-both i').css('display', 'inline');
            }

            if (SuperFilter.collision($('.price-range-min'), $('.price-range-max')) == true) {
                $('.price-range-min, .price-range-max').css('opacity', '0');
                $('.price-range-both').css('display', 'block');
            } else {
                $('.price-range-min, .price-range-max').css('opacity', '1');
                $('.price-range-both').css('display', 'none');
            }
        },
        change: function (event, ui) {
            $(this).attr('data-min', ui.values[0]);
            $(this).attr('data-max', ui.values[1]);
            SuperFilter.filter($parent);
        }
    });

   /* $('.ui-slider-range').append('<span class="price-range-both value"><i>' + SuperFilter.price($parent, $parent.find('.slider').slider('values', 0 )) + ' - </i>' + SuperFilter.price($parent, $parent.find('.slider').slider('values', 1 )) + '</span>');*/
	
    $('.ui-slider-handle:eq(0)').html('<span class="price-range-min value">' + SuperFilter.price($parent, $parent.find('.slider').slider('values', 0 )) + '</span>');
    $('.ui-slider-handle:eq(1)').html('<span class="price-range-max value">' + SuperFilter.price($parent, $parent.find('.slider').slider('values', 1 )) + '</span>');
};
//
//SuperFilter.setNavigation = function () {
//    /* sort and limit events */
//    $('.sort select, .limit select').removeAttr('onchange');
//
//    /* display product grid */
//    display($.totalStorage('display'));
//};